package com.csii.security.controller;

import cn.hutool.core.util.RandomUtil;
import com.csii.base.result.Result;
import com.csii.core.exception.AppException;
import com.csii.security.authentication.mobile.SmsSend;
import com.csii.security.properites.SecurityConstants;
import com.csii.user.entity.SysUser;
import com.csii.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 关于手机登录控制层
 * @Auther: ian
 */
@Controller
@Slf4j
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISysUserService sysUserService;
    @Value("${csii.mobile.expireTime:15}")
    private Long expireTime;

    /**
     * 前往手机验证码登录页
     * @return
     */
    @GetMapping("/mobile/page")
    public String toMobilePage() {
        return "login-mobile"; // templates/login-mobile.html
    }

    @Autowired
    SmsSend smsSend;

    /**
     * 发送手机验证码
     * @return
     */
    @ResponseBody //响应json字符串
    @GetMapping("/code/mobile")
    public Result loginSmsCode(HttpServletRequest request, @RequestParam String mobile) {
        SysUser user = sysUserService.getUserByPhone(mobile);
        if (user == null){
            throw new AppException("手机号码不存在");
        }
        // 1. 生成一个手机验证码MobileValidateFilter.
        String code = RandomUtil.randomNumbers(4);
        log.info("短信发送--------手机号:"+mobile+"----验证码:"+code);
        // 2. 将手机验证码保存到redis中
        redisTemplate.opsForValue().set(SecurityConstants.MOBILE_REDIS_KEY+mobile,code,expireTime, TimeUnit.MINUTES);
        // 3. 发送验证码到用户手机上
        smsSend.sendSms(mobile, code);

        return Result.ok();
    }

    @ResponseBody //响应json字符串
    @GetMapping("/register/code/mobile")
    public Result smsCode(HttpServletRequest request, @RequestParam String mobile) {
        // 1. 生成一个手机验证码MobileValidateFilter.
        String code = RandomUtil.randomNumbers(4);
        log.info("短信发送--------手机号:"+mobile+"----验证码:"+code);
        // 2. 将手机验证码保存到redis中
        redisTemplate.opsForValue().set(mobile,code,expireTime, TimeUnit.MINUTES);
        // 3. 发送验证码到用户手机上
        smsSend.sendSms(mobile, code);

        return Result.ok();
    }
}
